package customtags;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;



import dao.AccesoLogDao;

@SuppressWarnings("serial")
public class NavegadoresTag extends TagSupport {
	
	public int doStartTag( ) throws JspException {		
		
		AccesoLogDao a = new AccesoLogDao();
		HashMap<String, Long> hashMap = a.navegadoresUtilizados();
		Long totalNav = a.cantidadAccesos();

		DefaultPieDataset data = new DefaultPieDataset();		
		Iterator it = hashMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry e = (Map.Entry)it.next();
			Long cantNav = (Long) e.getValue();
			double x=cantNav.doubleValue();
	        double y=totalNav.doubleValue();
	        double porcentaje=(x*100.00)/y;
	        data.setValue((Comparable)e.getKey()+" Accesos: "+cantNav, porcentaje);			
		}
		
		// create a chart...
		JFreeChart chart = ChartFactory.createPieChart(
		"Accesos por navegador",
		data,
		true, // legend?
		true, // tooltips?
		false // URLs?
		);
		
		try {			
			String realPath = pageContext.getServletContext().getRealPath("/");
			String path = pageContext.getServletContext().getContextPath();
			
			ChartUtilities.saveChartAsJPEG(new File(realPath+"/Paginas/Gerencial/navegadores.jpg"), chart, 800, 500);
		    JspWriter out=pageContext.getOut();            
            out.print("<img alt='grafico' src='"+path+"/Paginas/Gerencial/navegadores.jpg' />");		
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
}
